package com.bookmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmall.product.domain.BookInfoImages;
import com.bookmall.product.mapper.BookInfoImagesMapper;
import com.bookmall.product.service.IBookInfoImagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author 胡菜鸡
 * @Create 2022-03-12-20:44
 */
@Service("bookInfoImagesService")
public class BookInfoImagesServiceImpl extends ServiceImpl<BookInfoImagesMapper,BookInfoImages> implements IBookInfoImagesService {

    @Autowired
    private BookInfoImagesMapper bookImagesMapper;

    /**
     * 通过图片地址集合插入书籍图片信息
     * @author 胡菜鸡
     * @date 2022/3/12 21:40
     */
    @Override
    public int insertImagesWithUrl(String imagesUrl, String bookId, int imageType) {
        //将图片地址集合转化为数组形式
        List<String> imagesList = Arrays.asList(imagesUrl.split(","));
        //映射成为书籍图片对象
        List<BookInfoImages> collect = imagesList.stream().map(imageUrl -> {
            //从图片地址中截取出图片名称
            String imageName = imageUrl.substring(imageUrl.indexOf("_") + 1);

            BookInfoImages bookImages = new BookInfoImages();
            bookImages.setBookId(bookId);
            bookImages.setImageName(imageName);
            bookImages.setImageUrl(imageUrl);
            bookImages.setImageSort(1);
            bookImages.setDefaultImage(1);
            bookImages.setImageType(imageType);
            return bookImages;
        }).collect(Collectors.toList());

        //将其中前两张图片转化为默认图片
        if(collect != null){
            collect.get(0).setDefaultImage(0);
            if(collect.size() > 1){
                collect.get(1).setDefaultImage(0);
            }
        }

        if(this.saveBatch(collect)) return 1;
        return 0;
    }

    /**
     * 通过书籍/求购 id 搜索图片
     * @author 胡菜鸡
     * @date 2022/3/14 22:14
     * @param
     * @return
     */
    @Override
    public String selectImageUrl(String bookId) {
        LambdaQueryWrapper<BookInfoImages> wrapper = new LambdaQueryWrapper<>();
        List<BookInfoImages> bookInfoImages = bookImagesMapper.selectList(wrapper.eq(BookInfoImages::getBookId, bookId));
        if(bookInfoImages != null && bookInfoImages.size() > 0){
            String imagesList = bookInfoImages.stream()
                    .map(bookImageEntity -> bookImageEntity.getImageUrl())
                    .collect(Collectors.toList()).toString();
            String imagesUrl = imagesList.replace("[", "").replace("]", "");
            return imagesUrl;
        }
        return null;
    }
}
